package com.project.service.util;

import com.project.service.server.Servlet;

import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * servlet工厂类
 */
public class ServletFactory {
    private static Properties pro = new Properties();
    private static Map<String,Servlet> servletMap = new HashMap<>();
    static {
        try {
            pro.load(new FileReader("web.txt"));

            //得到属性文件的键集合
            Set<String> keySet = pro.stringPropertyNames();
            for(String key : keySet){
                //根据键，得到值
                String classPath = pro.getProperty(key);
                //加载类，得到类模版
                Class c = Class.forName(classPath);

                servletMap.put(key,(Servlet)c.getConstructor().newInstance());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据URL，得到servlet实现类对象
     * @param url 客户端请求的URL
     * @return servlet对象
     */
    public static Servlet getServlet(String url){


        return servletMap.get(url);
    }

    public static void main(String[] args) {
        Servlet s = ServletFactory.getServlet("findAll");
        Servlet s1 = ServletFactory.getServlet("findAll");
        System.out.println(s == s1);
    }
}
